﻿using System;
using System.Collections.Generic;
using System.Text;
using Clipping.Infrastructure.Interfaces;
using Clipping.Infrastructure.Models;

namespace Clipping.SearchEnginePageParsers
{
    public class QihooPageParser : ISearchEnginePageParse
    {
        public void Parse(string html, out List<Infrastructure.Models.News> news, out string nextPageUrl)
        {
            news = new List<News>();
            nextPageUrl = null;
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);

            var liNav = doc.CreateNavigator();

            var divContentSearch = liNav.Select("//ul[@id='news']//li");
            while (divContentSearch.MoveNext())
            {
                News n = new News();

                var li = divContentSearch.Current;

                //取标题和链接
                var linkNode = li.SelectSingleNode("descendant::dt[@class='title']/a");
                if (linkNode != null)
                {
                    n.Title = linkNode.Value;
                    n.Url = linkNode.GetAttribute("href", "");
                    if (!string.IsNullOrEmpty(n.Url))
                        n.Url = System.Web.HttpUtility.HtmlDecode(n.Url);
                }

                //取时间
                var dtNode = li.SelectSingleNode("descendant::dt[@class='title']/span");
                n.PubDate = dtNode.Value;

                //取摘要
                var summaryNode = li.SelectSingleNode("descendant::dd[@class='content']");
                if (summaryNode != null)
                {
                    n.Summary = summaryNode.Value;
                }


                //取作者和来源
                var infoNode = li.SelectSingleNode("descendant::dd[@class='info']");
                if (infoNode != null)
                {
                    var aNode = infoNode.SelectSingleNode("descendant::a");
                    n.Media = aNode.Value;
                }
                news.Add(n);
            }


            var nextPage = liNav.SelectSingleNode("//a[@class='next']");
            if (nextPage != null && nextPage.Value != null && nextPage.Value.Contains("下一页"))
            {
                nextPageUrl = nextPage.GetAttribute("href", "");
                if (!string.IsNullOrEmpty(nextPageUrl))
                    nextPageUrl = System.Web.HttpUtility.HtmlDecode(nextPageUrl);
            }

        }
    }
}
